package com.myrice.remote.spring;

import java.util.Properties;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;

import com.myrice.core.Context;
import com.myrice.remote.Exportor;
import com.myrice.remote.impl.DefaultRemoteMethodCollection;
import com.myrice.remote.impl.DefaultServiceObject;
import com.myrice.utils.ConfigUtils;

public class SpringBeansExportor implements Exportor {

	public void destory(Context app) {
		String export = p.getProperty("export");
		if (export == null)
			return;
		String[] beanNames = export.split(",");
		for (String beanName : beanNames) {
			String handle = p.getProperty(beanName + ".handle", beanName);
			DefaultServiceObject so = (DefaultServiceObject) app
					.removeAttribute(DefaultRemoteMethodCollection
							.mappingInvokeHandle(handle));
			if (so != null) {
				so.destroy();
			}
		}
	}

	public static void export(Context app, ApplicationContext beans,
			Properties p) {
		String export = p.getProperty("export");
		if (export == null)
			return;
		String[] beanNames = export.split(",");
		for (String beanName : beanNames) {
			Object instance = beans.getBean(beanName);
			Class<?>[] interfaces = instance.getClass().getInterfaces();
			String handle = p.getProperty(beanName + ".handle", beanName);
			String interfacesArg = p.getProperty(beanName + ".interfaces", "")
					.trim();
			if (!interfacesArg.equals("")) {
				interfaces = ConfigUtils.parseInterfaces(interfacesArg);
			}
			DefaultServiceObject so = new DefaultServiceObject(handle,
					instance, interfaces);
			so.init();
			app.setAttribute(so.getInvokeHandle(), so);
			log.debug("export spring bean:" + beanName + "  =  " + instance);
		}
	}

	public void export(Context app) {
		export(app, beans, p);
	}

	public SpringBeansExportor(ApplicationContext beans, String exportLocation) {
		this.beans = beans;
		this.p = ConfigUtils.load(exportLocation, "utf-8");
	}

	private Properties p;
	private ApplicationContext beans;

	private static final Logger log = Logger
			.getLogger(SpringBeansExportor.class);
}
